package cn.edu.xmu.restfuldemo.dao;
import  cn.edu.xmu.restfuldemo.mapper.OrdersMapper;

import  cn.edu.xmu.restfuldemo.model.Orders;
import  cn.edu.xmu.restfuldemo.model.OrderItem;
import  cn.edu.xmu.restfuldemo.model.OrderItemPo;
import  cn.edu.xmu.restfuldemo.model.OrdersPo;
import  cn.edu.xmu.restfuldemo.util.ReturnObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;


@Repository
public class OrdersDao {

    @Autowired
    private OrdersMapper orderMapper;

    public ReturnObject<List<Orders>> fineorder(OrdersPo orderPo) {

        List<OrdersPo> orderPos = orderMapper.fineorder(orderPo);
        List<Orders> orders = new ArrayList<>(orderPos.size());
        for (OrdersPo orderPoItem : orderPos) {
            Orders order = new Orders(orderPoItem);
            List<OrderItemPo> orderItemPos = orderPo.getOrderItems();
            ArrayList<OrderItem> orderItems = new ArrayList<>(orderItemPos.size());
            for (OrderItemPo orderItemPo : orderItemPos) {
                orderItems.add(new OrderItem(orderItemPo));
            }
            order.setOrderItems(orderItems);
            orders.add(order);
        }
        return new ReturnObject<>(orders);
    }

    public ReturnObject<Orders> createOrder(Orders order){
        OrdersPo orderPo = order.getordersPo();
        orderMapper.createOrder(orderPo);
        if(null!=order.getOrderItems()){
            for(OrderItem orderItem:order.getOrderItems()){
                OrderItemPo orderItemPo =orderItem.getOrderItemPo();
                orderItemPo.setOrderId(orderPo.getId());
                Integer ret =  orderMapper.createOrderItem(orderItemPo);
            }
        }
        return new ReturnObject<>(order);
    }
}
